package com.fingard.dsp.bank.directbank.nbcb01;

import com.alibaba.fastjson.JSON;
import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptMapping;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.bankInterface.IScheduleTask;
import com.fingard.io.FileHelper;
import com.fingard.net.FormSubmit;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.util.SmbFileUtil;
import com.fingard.util.ZipHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * @author Marlon
 * @date 2018/9/18
 */
public class NBCB01ScheduleTask extends NBCB01Base implements IScheduleTask {

    static Object lockMutex = new Object();

    @Override
    public void execTask(final TaskTimerSet timerSet) {

        if (timerSet.taskNameList.toLowerCase().contains("pushreceipt")) {
            synchronized (lockMutex) {
                try {
                    qryReceipt();
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private String receiptSaveToMainDir = "";

    public void qryReceipt() {

        try {
            receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
            if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                    if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                        getStatement();
                    } else {
                        WriteBankLogLn("DSPSystem未配置回单文件推送地址");
                    }
                } else {
                    WriteBankLogLn("DSPSystem未配置回单文件共享目录");
                }
            } else {
                WriteBankLogLn("DSPSystem未配置回单文件下载保存主目录");
            }
        } catch (Exception e) {
            WriteBankLogLn(e);
        }
    }


    private void getStatement() {
        try {
            int counts = 0;
            String path = FGBiz.dspCenter.dspSet.dataDirPath + File.separator + "datafile" + File.separator + bankFront.code + File.separator + "receiptdatafile" + File.separator;
            File file = new File(path);
            File[] tempList = file.listFiles();
            if (tempList == null || tempList.length == 0) {
                WriteBankLogLn("文件夹没有需要下载电子回单的账户文件夹" + path);
                return;
            }
            //发银行报文的XML对象
            XmlTextWriter xmlWriter = null;
            HashMap<String, List<File>> fileMapList = null;
            for (File files : tempList) {
                Map<String, ReceiptMapping> receiptMappingMap = new HashMap<String, ReceiptMapping>();//用于存放回单信息

                List<StringBuilder> jsonList = new ArrayList<StringBuilder>();//json集合，用于统计全部回单数据，推送ats
                //StringBuilder json = new StringBuilder();
                //json.append("transType=downloadreceipt&data={\"rows\":[");
                fileMapList = new HashMap<String, List<File>>();
                String dataFilePath = path + files.getName() + File.separator + files.getName() + "_" + Format.Date8Format.format(new Date()) + ".txt";
                String fileContent = "";
                if (FileHelper.existFile(dataFilePath)) {
                    fileContent = FtpUtil.getTextFromFile(dataFilePath, getCharset());
                }
                WriteBankLogLn("读取到的内容为：" + fileContent);
                String dataFilePathSucc = path + files.getName() + File.separator + files.getName() + "_" + Format.Date8Format.format(new Date()) + "_Success.txt";
                String fileContentSucc = "";
                if (FileHelper.existFile(dataFilePathSucc)) {
                    fileContentSucc = FtpUtil.getTextFromFile(dataFilePathSucc, getCharset());
                }
                //记录需要上传的回单信息
                StringBuilder sbd = new StringBuilder();
                //写入通用的头部节点
                serviceId = "srv194_queryReceiptOrder";//客户回单信息查询
                String[] receiptCodes = fileContent.split("\r\n");
                if (receiptCodes.length > 0 && !"".equals(receiptCodes[0])) {
                    for (String receiptCode : receiptCodes) {
                        if (fileContentSucc.contains(receiptCode)) {
                            WriteBankLogLn("查询序列号：" + receiptCode + "已成功上传电子回单，如需重新推送请删除文件" + dataFilePathSucc + "中的" + receiptCode);
                            continue;
                        }
                        //处理并发
                        //synchronized (lockMutex) {
                        String[] accountInfo = receiptCode.split("\\|");
                        WriteBankLogLn(accountInfo[2] + "本次请求开始时间：" + new Date());
                        Thread.sleep(10000);
                        xmlWriter = new XmlTextWriter();
                        writeCommonHeader(xmlWriter);
                        xmlWriter.writeElementString("functionId", "srv194");
                        xmlWriter.writeElementString("functionName", "回单生成状态查询");
                        xmlWriter.writeStartElement("opReq");
                        xmlWriter.writeElementString("serialNo", getQryTransID());
                        xmlWriter.writeElementString("reqTime", Format.DateTime14Format.format(new Date()));
                        xmlWriter.writeStartElement("ReqParam");
                        xmlWriter.writeElementString("JYXH", accountInfo[2]);//查询序号
                        xmlWriter.writeEndElement();
                        xmlWriter.writeEndElement();
                        String signXml = getDataSignData(xmlWriter);
                        if (signnatrue(signXml)) {
                            xmlWriter.writeElementString("signData", signature);
                            xmlWriter.writeEndDocument();
                            WriteBankLogLn("回单生成状态查询发送银行报文：" + xmlWriter.toXmlString());
                            String[] tmpStrRet = sendToBank(getDataSendBank(xmlWriter.toXmlString()));//发送银行
                            if (tmpStrRet[0].length() == 0) {
                                StringBuilder tmpSbMsg = new StringBuilder();
                                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                                if (tmpBkReader != null) {
                                    String respCode = tmpBkReader.getFirstText("/NBCBEBankData/retCode");
                                    String respInfo = tmpBkReader.getFirstText("/NBCBEBankData/errorMsg");
                                    if (respCode != null && isActiveRetCode(respCode)) {
                                        StringBuilder receiptFilePaths = null;
                                        while (tmpBkReader.read("/NBCBEBankData/opRep/opResult")) {
                                            String returnCode = tmpBkReader.readedXElement.getSingleText("ZLZT");//应答代码
                                            String receiptFilePath = tmpBkReader.readedXElement.getSingleText("WJDZ");//文件地址
                                            if ("1".equals(returnCode)) {
                                                receiptFilePaths = new StringBuilder();
                                                String receiptDate = tmpBkReader.readedXElement.getSingleText("SCSJ");//生成时间
                                                receiptFilePaths = receiptFilePaths.append(receiptFilePath).append("|");
                                                //记录返回个数
                                                WriteBankLogLn("查询序号：" + accountInfo[2] + "获取的回单文件地址为：" + receiptFilePaths);
                                                System.out.println("查询序号：" + accountInfo[2] + "获取的回单文件地址为：" + receiptFilePaths);
                                                counts++;
                                            } else if ("0".equals(returnCode)) {
                                                WriteBankLogLn("回单文件生成中" + receiptFilePath);
                                            } else {
                                                WriteBankLogLn("回单文件生成失败");
                                            }

                                        }
                                        if (receiptFilePaths != null) {
                                            fileMapList.put(receiptCode, downloadReceiptFile(receiptFilePaths.toString(), receiptMappingMap));
                                        }
                                    } else {
                                        WriteBankLogLn(respInfo);
                                    }
                                } else {
                                    WriteBankLogLn(tmpSbMsg.toString());
                                }
                            } else {
                                WriteBankLogLn(tmpStrRet[1]);
                            }
                        } else {
                            WriteBankLogLn(tmpSign[1]);
                        }
                        WriteBankLogLn(accountInfo[2] + "本次请求结束时间：" + new Date());
                        sbd.append(receiptCode).append("\r\n");
                        //}
                    }
                    int tmpFileCount = 0;
                    for (String eachKey : fileMapList.keySet()) {
                        for (int i = 0; i < fileMapList.get(eachKey).size(); i++) {
                            String[] receiptFileName = eachKey.split("\\|");

                            String tmpByDate = Format.Date8Format.format(new Date());
                            tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/" + reqHeader.bankCode + "/";
                            int result = -1;
                            String AtsFilePath = "";
                            String name = fileMapList.get(eachKey).get(i).getName();
                            tmpByDate = tmpByDate + receiptFileName[0] + "/";
                            String uploadType = SmbFileUtil.getUploadType();
                            if (fileMapList.get(eachKey).get(i).exists() && fileMapList.get(eachKey).get(i).getName().contains(".pdf")) {
                                if (!"false".equalsIgnoreCase(uploadType) && !"sftp".equalsIgnoreCase(uploadType)) {
                                    if ("smb".equalsIgnoreCase(uploadType)) {
                                        WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                        result = SmbFileUtil.smbUploading(fileMapList.get(eachKey).get(i).getPath(), tmpByDate, FGBiz.dspCenter.dspSet.receiptShareDir);
                                        AtsFilePath = tmpByDate + fileMapList.get(eachKey).get(i).getName();
                                    } else if ("localhost".equalsIgnoreCase(uploadType)) {
                                        String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                        WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                        result = FileHelper.copyFile(fileMapList.get(eachKey).get(i).getPath(), shareDir + tmpByDate + tmpByDate + fileMapList.get(eachKey).get(i).getName());
                                        AtsFilePath = tmpByDate + tmpByDate + fileMapList.get(eachKey).get(i).getName();
                                    } else {
                                        tmpByDate = tmpByDate.replaceAll(reqHeader.bankCode + "/", "");
                                        WriteBankLogLn("正在上传文件至微服务:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                        Map<String, String> mapResult = FormSubmit.fileUpload
                                                (FGBiz.dspCenter.dspSet.receiptShareDir, receiptMappingMap.get(fileMapList.get(eachKey).get(i).getName()).ownAct, fileMapList.get(eachKey).get(i).getPath(), tmpByDate, tmpByDate + fileMapList.get(eachKey).get(i).getName(), getCharset());
                                        WriteBankLogStep3(JSON.toJSONString(mapResult));
                                        if (mapResult.keySet().size() != 0) {
                                            result = Integer.valueOf(mapResult.get("respCode"));
                                            tmpByDate = mapResult.get("remotePath");
                                            AtsFilePath = tmpByDate;
                                        } else {
                                            result = -1;
                                        }
                                    }
                                } else {//上传FTP/SFTP
                                    FtpSet ftpSet = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                    WriteBankLogLn("正在上传文件至" + ("false".equalsIgnoreCase(uploadType) ? "ftp" : "sftp") + "目录:" + ftpSet.upDir);
                                    //上传ftp服务器的地址
                                    String ftpFilePath = StringHelper.trimEndFileSp(ftpSet.upDir) + "/" + tmpByDate + fileMapList.get(eachKey).get(i).getName();
                                    WriteBankLogLn("开始将回单" + fileMapList.get(eachKey).get(i).getPath() + "上传至" + ftpFilePath);
                                    if ("false".equalsIgnoreCase(uploadType)) {
                                        //上传至ftp
                                        result = FtpUtil.ftpUploading(ftpSet, fileMapList.get(eachKey).get(i).getPath(), ftpFilePath);
                                    } else if("sftp".equalsIgnoreCase(uploadType)){//上传到SFTP
                                        result = FtpUtil.sftpUploading(ftpSet, fileMapList.get(eachKey).get(i).getPath(), ftpFilePath);
                                    }else{
                                        WriteBankLogLn("不支持的上传方式，请重新配置DSPSystem.xml中receiptShareDir文件上传方式");
                                        throw new RuntimeException("不支持的上传方式，请重新配置DSPSystem.xml中receiptShareDir文件上传方式");
                                    }
                                    AtsFilePath = tmpByDate + fileMapList.get(eachKey).get(i).getName();
                                }
                            }
                            if (result == 0 || result == 1) {
                                tmpFileCount++;
                                WriteBankLogLn("文件上传成功");
                                //=========回单新模式增加代码=======
                                if (isActive(receiptFileName[1])) {
                                    WriteBankLogLn("使用新回单模式");
                                    ReceiptMapping receiptMapping = receiptMappingMap.get(fileMapList.get(eachKey).get(i).getName());
                                    if (receiptMapping != null) {
                                        //推送数据给ATS处理
                                        StringBuilder json = new StringBuilder();
                                        json.append("{");
                                        json.append("\"actNum\":\"" + receiptMapping.ownAct + "\",");
                                        json.append("\"actCur\":\"" + receiptMapping.cur + "\",");
                                        json.append("\"receiptCode\":\"" + receiptMapping.receiptNo + "\",");//回单编号
                                        json.append("\"receiptType\":\"" + "" + "\",");//回单类型  1：存款回单；2：取款回单；3：转账回单；4：缴税回单；5：收费回单；6定期回单；7：活期回单
                                        json.append("\"receiptState\":\"" + "" + "\",");//回单状态 1：正常；2：冲正；3：被冲正；4：当日冲正
                                        json.append("\"oppActName\":\"" + receiptMapping.oppActName + "\",");
                                        json.append("\"oppActNum\":\"" + receiptMapping.oppActNum + "\",");
                                        json.append("\"amount\":\"" + receiptMapping.amount + "\",");
                                        json.append("\"moneyway\":\"" + "" + "\",");
                                        json.append("\"tranSeqNo\":\"" + receiptMapping.busRef + "\",");//
                                        json.append("\"tranCode\":\"" + "" + "\",");//交易码
                                        json.append("\"tranDate\":\"" + Format.Date10Format.format(Format.Date8Format.parse(receiptFileName[1])) + "\",");
                                        json.append("\"filePath\":\"" + AtsFilePath + "\",");//回单文件仓库存储路径
                                        json.append("\"fileType\":\"1\"");
                                        json.append("},");
                                        jsonList.add(json);
                                    } else {
                                        WriteBankLogLn("此回单文件" + fileMapList.get(eachKey).get(i).getPath() + "未关联上回单信息，说明是已经上传过了的回单");
                                    }
                                    //=========回单新模式增加代码=======
                                } else {
                                    WriteBankLogLn("使用原回单模式");
                                    String[] content = name.replaceAll(".pdf", "").split("_");
                                    //推送数据给ATS处理
                                    StringBuilder json = new StringBuilder();
                                    json.append("{");
                                    json.append("\"actNum\":\"" + receiptFileName[0] + "\",");
                                    json.append("\"actCur\":\"" + getBankConfig().getMapKeyByValue("curActMapping", receiptFileName[0]) + "\",");
                                    //拼接回单编号确定唯一
                                    String receiptCode = "";
                                    if (content.length > 1) {
                                        StringBuffer sb = new StringBuffer(receiptFileName[0]).append(content[2]);
                                        if (content[3].trim().length() < 4) {
                                            for (int j = 4; j > content[3].trim().length(); j--) {
                                                sb.append("0");
                                            }
                                        }
                                        sb.append(content[3]);
                                        receiptCode = sb.toString();
                                    } else {
                                        receiptCode = name.substring(0, name.indexOf("."));
                                    }
                                    json.append("\"receiptCode\":\"" + receiptCode + "\",");//回单编号
                                    json.append("\"receiptType\":\"" + "" + "\",");//回单类型  1：存款回单；2：取款回单；3：转账回单；4：缴税回单；5：收费回单；6定期回单；7：活期回单
                                    json.append("\"receiptState\":\"" + "" + "\",");//回单状态 1：正常；2：冲正；3：被冲正；4：当日冲正
                                    json.append("\"oppActName\":\"" + "" + "\",");
                                    json.append("\"oppActNum\":\"" + "" + "\",");
                                    json.append("\"amount\":\"" + "" + "\",");
                                    json.append("\"moneyway\":\"" + "" + "\",");
                                    json.append("\"tranSeqNo\":\"" + reqHeader.transSeqID + "\",");//
                                    json.append("\"tranCode\":\"" + "" + "\",");//交易码
                                    json.append("\"tranDate\":\"" + Format.Date10Format.format(Format.Date8Format.parse(receiptFileName[1])) + "\",");
                                    json.append("\"filePath\":\"" + tmpByDate + fileMapList.get(eachKey).get(i).getName() + "\",");//回单文件仓库存储路径
                                    json.append("\"fileType\":\"1\"");
                                    json.append("},");
                                    jsonList.add(json);
                                }
                            } else {
                                WriteBankLogLn("上传文件至共享目录失败，请检查共享目录配置是否正确");
                            }
                        }
                    }
                    WriteBankLogLn("银行返回了" + counts + "个回单文件，成功保存了" + tmpFileCount + "个文件");
                    //分批推送ats，一批500，按原逻辑处理
                    if (tmpFileCount > 0 && jsonList.size() > 0) {
                        String sendStr = null;
                        if (this.getBankConfig().getValueAsBool("receiptPushHasTenantId")) {
                            sendStr = "tenantId=" + FGBiz.dspCenter.dspSet.tenant + "&transType=downloadreceipt&data={\"rows\":[";
                        } else {
                            sendStr = "transType=downloadreceipt&data={\"rows\":[";
                        }
                        StringBuilder sendJson = new StringBuilder();
                        String strValue = getBankConfig().getValueAsString("receiptDataCount");
                        if (StringHelper.isNullOrEmpty(strValue)) {
                            strValue = "500";
                        }
                        Integer receiptDataCount = Integer.valueOf(strValue);
                        boolean flag = false;
                        for (int i = 0; i < jsonList.size(); i++) {
                            if ((i + 1) % receiptDataCount == 0 || i == jsonList.size() - 1) {
                                jsonList.get(i).deleteCharAt(jsonList.get(i).length() - 1);
                                sendJson.append(jsonList.get(i));
                                sendJson.append("]}");
                                String[] data = sendToATS(sendStr + sendJson.toString());
                                if (data[0].length() == 0 && "ok".equals(data[1])) {
                                    WriteBankLogLn("========5、推送数据到ATS成功" + ((i + 1) % receiptDataCount > 0
                                            ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据========");
                                    flag = true;
                                } else {
                                    WriteBankLogLn("========5、推送数据到ATS失败" + ((i + 1) % receiptDataCount > 0
                                            ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请检查日志========");
                                }
                                sendJson = new StringBuilder();
                            } else {
                                sendJson.append(jsonList.get(i));
                            }
                        }
                        if (flag) {
                            generateReceiptFileSuccess(sbd.toString(), dataFilePath);
                        }
                    } else {
                        WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
                    }
                } else {
                    WriteBankLogLn("今日暂无查询回单记录");
                }
            }
        } catch (Exception e) {
            WriteBankLogLn(e);
        }
    }

    private List<File> downloadReceiptFile(String receiptFilePaths, Map<String, ReceiptMapping> receiptMappingMap) {

        List<File> receiptFile = new ArrayList<File>();
        try {
            HttpURLConnection connection = null;
            URL url = null;
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            String[] filePathArray = receiptFilePaths.split("\\|");// 通过“|”分割文件路径
            int fileNum = filePathArray.length;// 文件数量
            WriteBankLogLn("共" + fileNum + "个文件需要下载");
            String tmpByDate = Format.Date8Format.format(new Date());
            tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/" + reqHeader.bankCode + "/";
            for (int i = 0; i < fileNum; i++) {
                String filePath = filePathArray[i];
                String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length());// 文件名
                String fileUrl = bankFront.bankReceiptMainDir + "/" + filePath;// 完整文件url
                WriteBankLogLn("开始下载第" + (i + 1) + "个文件，服务端地址：" + fileUrl);
                System.out.println(filePath);
                String[] fileDir = filePath.split("/");
                String localPath = receiptSaveToMainDir + File.separator + tmpByDate + File.separator + fileDir[2] + File.separator + fileDir[3];
                if (!FileHelper.existFile(localPath)) {
                    FileHelper.mkdir(localPath);
                }
                File localFile = new File(localPath + File.separator + fileName);// 创建本地文件对象
                // 开始下载
                try {
                    url = new URL(fileUrl);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.connect();
                    bis = new BufferedInputStream(connection.getInputStream());
                    bos = new BufferedOutputStream(new FileOutputStream(localFile));
                    int len = 2048;
                    byte[] b = new byte[len];
                    while ((len = bis.read(b)) != -1) {
                        bos.write(b, 0, len);
                    }
                    bos.flush();
                    if (!"".equals(fileName) && fileName.contains(".zip")) {
                        //解压文件
                        WriteBankLogLn("下载文件为zip文件，开始解压" + localFile.getPath());
                        //=========回单新模式增加代码=======
                        String receiptDate = fileName.replace(".zip", "");//回单日期
                        //回单压缩包链接规则变更，使用新文件夹存储回单文件：file/查询发起日期/dlReceipt/客户号+账号/查询日期.zip
                        if (isActive(receiptDate)) {
                            localPath = receiptSaveToMainDir + File.separator + fileDir[3] + File.separator + receiptDate;
                            if (!FileHelper.existFile(localPath)) {
                                FileHelper.mkdir(localPath);
                            }
                        }
                        //=========回单新模式增加代码=======
                        ZipHelper.unzipFile(localFile.getPath(), localPath);
                        File file2 = new File(localPath + File.separator + fileName.substring(0, fileName.indexOf(".")));
                        for (File file : file2.listFiles()) {
                            //=========回单新模式增加代码=======
                            //解析回单信息
                            if (isActive(receiptDate) && file.getName().contains(".txt")) {
                                String receiptContent = FileHelper.readFileText(file.getPath(), "gbk");
                                WriteBankLogLn("获取到回单信息文件" + file.getPath() + "，信息为：\r\n" + receiptContent);
                                String[] receiptIfmation = receiptContent.split("\r\n");
                                for (String receipt : receiptIfmation) {
                                    WriteBankLogLn("开始处理回单信息：" + receipt);
                                    receipt.replaceAll("@\\\\\\|", "@@@");
                                    String[] receiptArr = receipt.split("@\\\\\\|");
                                    if (receiptArr.length > 11) {
                                        WriteBankLogLn("开始录入回单信息：" + receipt);
                                        ReceiptMapping receiptMapping = new ReceiptMapping();
                                        receiptMapping.receiptNo = receiptArr[1];//回单号
                                        receiptMapping.busRef = receiptArr[10];//业务参考号
                                        receiptMapping.amount = new BigDecimal(receiptArr[3]);//交易金额
                                        receiptMapping.cur = convertCurToATS(receiptArr[4]);//币种
                                        String date = receiptArr[5];
                                        date = date.substring(0, 4) + date.substring(5, 7) + date.substring(8, 10);
                                        receiptMapping.busDate = date.length() == 8 ? Integer.parseInt(date)
                                                : Integer.parseInt(localFile.getName().replace(".zip", ""));//回单日期
                                        receiptMapping.oppActName = receiptArr[8];//对方户名
                                        receiptMapping.oppActNum = receiptArr[6];//对方账号
                                        receiptMapping.ownAct = receiptArr[2];//本方账号
                                        receiptMapping.srcFile = receiptArr[11];//回单文件名
                                        receiptMappingMap.put(receiptMapping.srcFile, receiptMapping);
                                    }
                                }
                                //=========回单新模式增加代码=======
                            } else {
                                receiptFile.add(file);
                            }
                        }
                        //删除压缩包
                    /*
                    if (FileHelper.deleteFileIfExists(localFile.getPath())) {
                        WriteBankLogLn("已删除临时文件：" + localFile.getPath());
                    }*/
                    } else {
                        WriteBankLogLn("下载文件为pdf文件");
                        receiptFile.add(localFile);
                    }
                    WriteBankLogLn("下载成功！本地路径：" + localPath + File.separator + fileName.substring(0, fileName.indexOf(".")));
                } catch (Exception e) {
                    WriteBankLogLn("下载失败:" + e.toString());
                    e.printStackTrace();
                } finally {
                    try {
                        if (bis != null) {
                            bis.close();
                        }
                        if (bos != null) {
                            bos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        } catch (Exception e) {
            WriteBankLogLn("下载失败:" + e.toString());
            e.printStackTrace();
        }
        return receiptFile;
    }

    private void generateReceiptFileSuccess(String newFileContent, String filesPath) throws Exception {
        FileOutputStream fos = null;
        try {
            String filePath = filesPath.replace(".txt", "_Success.txt");
            File batFile = new File(filePath);
            if (!batFile.getParentFile().exists()) {
                batFile.getParentFile().mkdirs();
            }
            String fileContent = "";
            if (!batFile.exists()) {
                batFile.createNewFile();
            } else {
                fileContent = FtpUtil.getTextFromFile(filePath, getCharset());
                if (fileContent.contains(newFileContent)) {
                    return;
                }
            }
            fos = new FileOutputStream(batFile);
            fos.write(fileContent.concat(newFileContent).getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }

    /**
     * 校验回单时间是否在生效时间中
     *
     * @param receiptDates
     * @return
     */
    private boolean isActive(String receiptDates) {
        boolean flag = false;
        if ("true".equals(getBankConfig().getValueAsString("receiptNewMode"))
                && receiptDates.length() == 8) {
            //回单时间
            int receiptDate = Integer.parseInt(receiptDates);
            //生效时间
            int availDate = Integer.parseInt(getBankConfig().getValueAsString("blnAndridAvaiDate"));
            if (receiptDate >= availDate) {
                flag = true;
            }
        }
        return flag;
    }
}
